/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import xml.Parser;

/**
 *
 * @author gravena
 */
public class ConnectionListener implements Runnable {
    private DatagramSocket listener;
    private boolean systemRunning = true;
    private ArrayList<Slave> slaves;

    public ConnectionListener(ArrayList<Slave> slaves) {

        this.slaves = slaves;
        try {
            this.listener = new DatagramSocket(6023);
        } catch (SocketException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void run() {
        while(this.systemRunning) {
            try {
                System.out.println("Mestre iniciado, esperando conexões.");
                /* Prepare the buffer to receive the UDP packet. 512 bytes should be enough
                 * since only one type of XML message is received through a UDP connection.
                 */
                byte buf[] = new byte[512];
                DatagramPacket p = new DatagramPacket(buf, buf.length);
                
                /* A block call is done here, so this threads keep waiting for new connections.                 
                 */
                this.listener.receive(p);                
                this.listener.disconnect();

                /** TODO: Parse the integer on the start of the transmission
                 *
                 */

                System.out.println("Iniciando parser");
                String xmlIn = new String(buf);
                System.out.println(xmlIn);
                Parser parser = new Parser(xmlIn);                                
                
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }


        }
        this.listener.close();
    }

    public boolean addSlave(Slave slave) {
        return this.slaves.add(slave);
    }
    
}
